import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { ResponseFactory } from '../result/result.factory';
import * as FlakeId from 'flake-idgen';
import intformat = require('biguint-format');
import { UserDto } from './user.dto';
import { AuthService } from '../auth/auth.service';

@Injectable()
export class UserService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly authService: AuthService
  ) {}
  private flakeIdGen = new FlakeId();
  async register({ username, password, avatar }: UserDto) {
    const im_id = intformat(this.flakeIdGen.next(), 'dec');
    const userData = {
      username,
      password,
      im_id,
      create_time: new Date(),
      ...(avatar && { avatar }), // 只有当 avatar 存在时才添加
    };
    await this.prisma.user_info.create({ data: userData });
    return ResponseFactory.success(null, '注册成功，请登录');
  }

  async login({ username, password }: UserDto){
    const user = await this.prisma.user_info.findFirst({
      where: {
        username,
        password,
      },
    })
    if (!user) throw new UnauthorizedException('用户名或密码错误')
    const token = await this.authService.generateToken(user)
    return ResponseFactory.success({im_id: user.im_id, avatar: user.avatar, token},'登录成功')
  }
}
